import json
import re

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection
from apps.users.models import *
from meiduo_mall import settings

# Create your views here.
class QQLoginURLView(View):

    def get(self, request):
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=next)
        qq_login_url = qq.get_qq_url()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'login_url': qq_login_url})

from apps.oauth.models import OAuthQQUser
class OauthQQView(View):

    def get(self, request):
        code = request.GET.get('code')
        if not code:
            return JsonResponse({'code': 400, 'errmsg': '缺少code参数'})
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=next)
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:

            from apps.oauth.utils import generic_openid
            access_token = generic_openid(openid)
            response = JsonResponse({'code': 4000, 'access_token': access_token})
            return response

        else:
            login(request, qquser.user)
            resopnse = JsonResponse({'code': 0, 'errmsg': 'OK'})
            resopnse.set_cookie('username', qquser.user.username)
            return resopnse

    def post(self, request):
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')

        from apps.oauth.utils import check_access_token
        openid = check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 4000, 'errmsg': '无效的access_token'})

        if not all([mobile, password, sms_code, openid]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '请输入正确的手机号码'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '请输入8-20位的密码'})

        redis_conn = get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码已过期'})
        if sms_code != sms_code_server.decode():
            return JsonResponse({'code': 400, 'errmsg': '短信验证码错误'})
        try:
            user = User.objects.get(mobile=mobile)

        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)

        else:
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '密码错误'})

        OAuthQQUser.objects.create(user=user, openid=openid)
        login(request, user)
        resopnse = JsonResponse({'code': 0, 'errmsg': 'OK'})
        resopnse.set_cookie('username', user.username)
        return resopnse


# # 加密openid
# s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
# token = s.dumps({'openid': '1234567890'})
#
# # 解密openid
# s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
# s.loads(token)